/*
 * FileName：AccountFansCtrl.java
 * <p>
 * Copyright (c) 2017-2020, <a href="http://www.webcsn.com">hermit (794890569@qq.com)</a>.
 * <p>
 * Licensed under the GNU General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl-3.0.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.wxmp.wxcms.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wxmp.core.common.BaseCtrl;
import com.wxmp.core.exception.WxErrorException;
import com.wxmp.core.util.AjaxResult;
import com.wxmp.wxapi.process.MpAccount;
import com.wxmp.wxapi.process.WxApiClient;
import com.wxmp.wxapi.process.WxMemoryCacheClient;
import com.wxmp.wxcms.domain.AccountFans;
import com.wxmp.wxcms.domain.UserTag;
import com.wxmp.wxcms.service.AccountFansService;
import com.wxmp.wxcms.service.UserTagService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author hermit
 * @version 2.0
 * @date 2018-04-17 10:54:58
 */
@Controller
@RequestMapping("/accountfans")
public class AccountFansCtrl extends BaseCtrl {

    @Autowired
    private AccountFansService entityService;

    @Autowired
    private UserTagService userTagService;

    @RequestMapping(value = "/info")
    @ResponseBody
    public AjaxResult getById(String id) {
        AccountFans fans = entityService.getById(id);
        return AjaxResult.success(fans);
    }

    @RequestMapping(value = "/list")
    @ResponseBody
    public AjaxResult list(AccountFans searchEntity) {
        List<AccountFans> fansList = this.entityService.getFansListByPage(searchEntity);
        return getResult(searchEntity, fansList);
    }

    @RequestMapping(value = "/batchCreateTagging")
    @ResponseBody
    public AjaxResult batchCreateTagging(String openIds, String tagId) throws WxErrorException {
        MpAccount mpAccount = WxMemoryCacheClient.getMpAccount();//获取缓存中的唯一账号
        String[] arrays = openIds.split(",");
        Set<String> tagSet = new HashSet<>();
        tagSet.add(tagId);

        //删除用户所有标签
        for (String openId : arrays) {
            JSONObject openIdObj = new JSONObject();
            openIdObj.put("openid", openId);
            JSONObject userTagList = WxApiClient.userTagList(JSON.toJSONString(openIdObj), mpAccount);
            if (userTagList != null && userTagList.containsKey("tagid_list")) {
                JSONArray array = userTagList.getJSONArray("tagid_list");
                for (int i = 0; i < array.size(); i++) {
                    String deleteTagId = array.getString(i);
                    tagSet.add(deleteTagId);
                    JSONObject params = new JSONObject();
                    JSONArray openIdArray = new JSONArray();
                    if (StringUtils.isNotBlank(openId) && !"null".equals(openId)) {
                        openIdArray.add(openId);
                    }
                    params.put("openid_list", openIdArray);
                    params.put("tagid", deleteTagId);
                    JSONObject resultObj = WxApiClient.batchCancleTagging(JSON.toJSONString(params), mpAccount);
                    System.out.println(JSON.toJSONString(resultObj));
                }
            }
        }

        JSONObject params = new JSONObject();
        JSONArray array = new JSONArray();
        for (String openId : arrays) {
            if (StringUtils.isNotBlank(openId) && !"null".equals(openId)) {
                array.add(openId);
            }
        }
        params.put("openid_list", array);
        params.put("tagid", tagId);
        System.out.println(JSON.toJSONString(params));
        JSONObject resultObj = WxApiClient.batchCreateTagging(JSON.toJSONString(params), mpAccount);
        if (resultObj.getIntValue("errcode") == 0) {
            for (String str : tagSet) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("tagid", str);
                jsonObject.put("next_openid", "");
                JSONObject jsonObjUserList = WxApiClient.getUserListByTag(jsonObject.toString(), mpAccount);
                if (jsonObjUserList != null && jsonObjUserList.containsKey("count")) {
                    int count = jsonObjUserList.getIntValue("count");
                    UserTag userTag = userTagService.getById(Integer.parseInt(str));
                    userTag.setCount(count);
                    userTagService.update(userTag);
                }
            }
            return AjaxResult.success();
        } else {
            return AjaxResult.failure(resultObj.getString("errmsg"));
        }
    }

    @RequestMapping(value = "/batchCancleTagging")
    @ResponseBody
    public AjaxResult batchCancleTagging(String openIds, String tagId) throws WxErrorException {
        MpAccount mpAccount = WxMemoryCacheClient.getMpAccount();//获取缓存中的唯一账号
        String[] arrays = openIds.split(",");
        JSONObject params = new JSONObject();
        JSONArray array = new JSONArray();
        for (String openId : arrays) {
            if (StringUtils.isNotBlank(openId) && !"null".equals(openId)) {
                array.add(openId);
            }
        }
        params.put("openid_list", array);
        params.put("tagid", tagId);
        System.out.println(JSON.toJSONString(params));
        JSONObject resultObj = WxApiClient.batchCancleTagging(JSON.toJSONString(params), mpAccount);
        if (resultObj.getIntValue("errcode") == 0) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("tagid", tagId);
            jsonObject.put("next_openid", "");
            JSONObject jsonObjUserList = WxApiClient.getUserListByTag(jsonObject.toString(), mpAccount);
            if (jsonObjUserList != null && jsonObjUserList.containsKey("count")) {
                int count = jsonObjUserList.getIntValue("count");
                UserTag userTag = userTagService.getById(Integer.parseInt(tagId));
                userTag.setCount(count);
                userTagService.update(userTag);
            }
            return AjaxResult.success();
        } else {
            return AjaxResult.failure(resultObj.getString("errmsg"));
        }
    }

}
